import axios from 'axios'
import qs from 'qs'
import {Toast} from 'vant'

axios.defaults.baseURL = 'http://sae.wecozhiku.com/'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

axios.interceptors.request.use(function (config) {
  Toast.loading({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
    loadingType: 'spinner'
  })
  return config
}, function (error) {
  return Promise.reject(error)
})

axios.interceptors.response.use(function (res) {
  Toast.clear()
  return res
}, function (error) {
  Toast.clear()
  return Promise.reject(error)
})

function doPost ({url, params, success}) {
  axios.post(url, qs.stringify(params))
    .then(res => {
      success(res)
    })
    .catch(() => {
      success({data: {message: '未知错误'}})
      Toast('未知错误')
    })
}

function doFormDate ({url, params, success}) {
  axios.post(url, params, {headers: {'Content-Type': 'multiple/form-data'}})
    .then(res => {
      success(res)
    })
    .catch(() => {
      success({error: true})
    })
}

export {
  doPost,
  doFormDate
}
